<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
      <!-- 搜索结果 -->
      <search-result
        v-if="isResultShow"
        :search-text="searchText"
      ></search-result>
      <!-- 搜索建议 -->
      <search-suggestion
        v-else-if="searchText"
        :search-text="searchText"
        @search="onSearch"
      ></search-suggestion>
      <!-- 搜索历史 -->
      <search-history 
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
      ></search-history>
    </form>
  </div>
</template>

<script>
import searchHistory from '@/views/search/components/search-history.vue';
import searchSuggestion from '@/views/search/components/search-suggestion.vue';
import searchResult from '@/views/search/components/search-result.vue';
export default {
  name: 'SearchIndex',
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  data() {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: [] // 储存历史记录
    };
  },
  methods: {
    onSearch(val) {
      this.searchText = val;

      const index = this.searchHistories.indexOf(val);
      
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }

      this.searchHistories.unshift(val);

      this.isResultShow = true;
    },
    onCancel() {
      this.$router.back();
    }
  }
};
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;

  .van-search__action {
    color: #fff;
  }

  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
